package com.admin.system.interceptor;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.admin.system.entity.SystemLog;
import com.admin.system.entity.SystemUser;
import com.admin.system.service.SystemLogService;
import com.admin.utils.IpUtils;

/**
 * 记录系统操作日志用户
 *
 * @author alex
 */
@Component
public class OperationLogInterceptor implements HandlerInterceptor {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    SystemLogService logService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String path = request.getServletPath();
        String ip = IpUtils.getIpAddr(request);
        String client = IpUtils.getOsAndBrowserInfo(request);
        JSONObject paramsJson = new JSONObject();
        //遍历请求的参数
        Map<String, String[]> params = request.getParameterMap();
        Iterator<String> it = params.keySet().iterator();
        while (it.hasNext()) {
            String key = it.next().toString();
            String[] values = params.get(key);
            if (values.length > 1) {
                paramsJson.put(key, values);
            } else {
                if ("password".equals(key)) {
                    paramsJson.put(key, "******");
                } else {
                    paramsJson.put(key, values[0]);
                }
            }
        }
        //存储后台用户操作日志
        SystemLog log = new SystemLog();
        log.setUrl(path);
        log.setClient(client);
        log.setIp(ip);
        log.setParams(paramsJson.toJSONString());
        try {
            //获取当前用户
            Subject subject = SecurityUtils.getSubject();
            SystemUser loginUser = (SystemUser) subject.getPrincipal();
            if (loginUser != null) {
                log.setUserId(loginUser.getId());
            }
        } catch (UnavailableSecurityManagerException usme) {
            //获取用户登录用户信息异常
            logger.info("用户未登陆操作");
        }
        logService.add(log);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

}
